import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  //const apiBaseUrl = env.VITE_API_BASE_URL || 'https://u9.yhroot.com'
  const apiBaseUrl = 'https://u9.yhroot.com'
  
  return {
    plugins: [vue()],
    server: {
      host: '0.0.0.0', // 允许局域网访问
      port: 5173,      // 指定端口
      strictPort: true, // 端口被占用时不自动切换
      proxy: {
        // SMIS配料岛库存代理 - 正式环境
        '/api/smis': {
          target: 'http://smis.yhroot.com',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api\/smis/, '/datacenter/productionline/scheduling/find'),
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('SMIS配料岛代理请求:', proxyReq.method, proxyReq.path)
              proxyReq.setHeader('Content-Type', 'application/json')
              proxyReq.setHeader('Accept', 'application/json')
            })
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log('SMIS配料岛代理响应:', proxyRes.statusCode, req.url)
              res.setHeader('Access-Control-Allow-Origin', '*')
              res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
              res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization')
            })
            proxy.on('error', (err, req, res) => {
              console.log('SMIS配料岛代理错误:', err.message)
            })
          }
        },
        // 物料库存专用代理
        '/api/u9/stock': {
          target: apiBaseUrl,
          changeOrigin: true,
          secure: true,
          rewrite: (path) => '/U9/RestServices/UFIDA.U9.Cust.YHHT.DomainMainSV.DataQueryReport.IQNanTongWhQoh.svc/do',
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('U9库存代理请求:', proxyReq.method, proxyReq.path)
              proxyReq.setHeader('Content-Type', 'application/json')
              proxyReq.setHeader('Accept', 'application/json')
            })
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log('U9库存代理响应:', proxyRes.statusCode, req.url)
              res.setHeader('Access-Control-Allow-Origin', '*')
              res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
              res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization')
            })
            proxy.on('error', (err, req, res) => {
              console.log('U9库存代理错误:', err.message)
            })
          }
        },
        // 专门为U9系统设置的代理
        '/api/u9': {
          target: apiBaseUrl,
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api\/u9/, '/U9/RestServices/UFIDA.U9.Cust.YHHT.DomainMainSV.DataQueryReport.IQMOPickInfo.svc'),
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('U9代理请求:', proxyReq.method, proxyReq.path)
              // 设置必要的请求头
              proxyReq.setHeader('Content-Type', 'application/json')
              proxyReq.setHeader('Accept', 'application/json')
            })
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log('U9代理响应:', proxyRes.statusCode, req.url)
              // 设置CORS头部
              res.setHeader('Access-Control-Allow-Origin', '*')
              res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
              res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization')
            })
            proxy.on('error', (err, req, res) => {
              console.log('U9代理错误:', err.message)
            })
          }
        },
        // 通用API代理
        '/api': {
          target: apiBaseUrl,
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log('通用代理请求:', proxyReq.method, proxyReq.path)
            })
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log('通用代理响应:', proxyRes.statusCode, req.url)
            })
          }
        }
      }
    },
    // 构建配置
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: false,
      minify: 'terser',
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'axios', 'pinia'],
            elementPlus: ['element-plus', '@element-plus/icons-vue'],
            xlsx: ['xlsx']
          }
        }
      }
    },
    // 预览服务器配置（用于预览构建后的应用）
    preview: {
      host: '0.0.0.0',
      port: 4173,
      strictPort: true
    }
  }
})
